import os
import pandas as pd
from flask import request, send_from_directory
from dash import get_app
from dash import (
    dcc,
    html,
    callback,
    Output,
    Input,
    State,
    register_page,
)
from ddbtools import BaseCRUD, DBDf, Filter, Comparator
from gypb.db import get_db
import feffery_antd_components as fac

app = get_app()
register_page(__name__, name="火富牛数据管理", order=1)
session = get_db()

dir = "/home/xuanqi/data/gypb/hfnnav"

needed_codes = [
    "SZZ881",
    "SZV309",
    "SADQ17",
    "SAFA33",
    "SB8975",
    "SADR78",
    "SB2832",
    "SZV387",
    "SB8919",
    "SAAC57",
    "SZU419",
    "SZT050",
    "STX548",
    "SZL216",
    "STP197",
    "SZV626",
    "SXE966",
    "SXV089",
    "SXR650",
    "SZG219",
    "SXM598",
    "SSU931",
    "SVH326",
    "STN410",
    "STK261",
    "SQE574",
    "STJ176",
    "SSV201",
    "SQR966",
    "SQL649",
    "SQC494",
    "SLJ142",
    "SLS999",
    "SLC998",
    "SJV111",
    "SJ0750",
    "T05424",
    "SVW716",
    "SVY358",
    "LW453A",
    "SZW030",
    "SVY007",
    "SSL649",
    "SNS720",
    "SLL697",
    "SNY211",
    "SQN990",
    "SSK627",
    "STB333",
    "SVF995",
    "SVT429",
    "SND029",
    "SCX395",
    "SSM234",
]


def get_nav(codes, start, end):
    crud = BaseCRUD("dfs://product", "attr_double")
    start = pd.to_datetime(start)
    end = pd.to_datetime(end)
    data = crud.get(
        session,
        conds=[
            Filter("code", Comparator.isin, codes),
            Filter("datetime", Comparator.gt, start),
            Filter("datetime", Comparator.lt, end),
            Filter("attribute", Comparator.isin, ["netvalue", "cum_netvalue"]),
        ],
    )
    cols = {"code":"备案号","datetime":"日期","netvalue":"单位净值","cum_netvalue":"累计净值"}
    data = data.reset_index().rename(columns=cols)
    data["备案号"] = data["备案号"].replace("T05424","SZ686B")
    data["日期"] = pd.to_datetime(data["日期"]).dt.date
    data = data.set_index(["备案号","日期"])[["单位净值","累计净值"]]
    return data


end = pd.Timestamp.now().strftime("%Y-%m-%d")
start = (pd.Timestamp.now() - pd.Timedelta(days=365)).strftime("%Y-%m-%d")
layout = html.Div(
    [
        fac.AntdDateRangePicker(
            id="date-range-picker",
            defaultValue=[start, end],
        ),
        # fac.AntdButton("查询",id="query-hfn-net-value"),
        fac.AntdButton("下载数据", id="button-download-hfn-net-value"),
        dcc.Download(id="download-hfn-net-value-xlsx"),
    ]
)


@callback(
    Output("download-hfn-net-value-xlsx", "data"),
    Input("button-download-hfn-net-value", "nClicks"),
    State("date-range-picker", "value"),
)
def download_hfn_net_value(nClicks, value):
    if nClicks:
        start, end = value
        df = get_nav(needed_codes, start, end)

        return dcc.send_data_frame(df.to_excel, f"火富牛净值上传_{start}_{end}.xlsx")